package com.thjk.bdf.preloan.service.domain.domainservice;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.thjk.bdf.common.base.BasicResp;
import com.thjk.bdf.common.enmus.ServiceEnum;
import com.thjk.bdf.common.entity.ApplyOrder;
import com.thjk.bdf.common.entity.ext.ApplyOrderApprovalReq;
import com.thjk.bdf.common.entity.ext.ApplyOrderScoreReq;
import com.thjk.bdf.common.entity.ext.ApplyOrderScreeningReq;
import com.thjk.bdf.common.request.CreditNotifyRequest;
import com.thjk.bdf.preloan.service.repository.dao.ApplyOrderMapper;

@Service
public class CreditNotifyService {
    private static final Logger logger = LoggerFactory.getLogger(CreditNotifyService.class);

    @Autowired
    private ApplyOrderMapper applyOrderMapper;

	@SuppressWarnings("unchecked")
	public BasicResp creditNotify(CreditNotifyRequest request) {
        
        BasicResp resp = BasicResp.back(ServiceEnum.SERVICE_SUCCESS.getCode(), ServiceEnum.SERVICE_SUCCESS.getDesc());
        ApplyOrder record = new ApplyOrder();
        try {
        	  //初篩通知(插入，更新)
            if(ServiceEnum.SCREENING_RESULT.getCode().equals(request.getEventType())) {
            	//Map<String,String> map=(Map<String, String>) request.getData();
            	//ApplyOrderScreeningReq req =  com.thjk.bdf.common.utils.BeanUtil.decode(ApplyOrderScreeningReq.class, map);
            	ApplyOrderScreeningReq req = JSONObject.parseObject(JSONObject.toJSONString(request.getData()), ApplyOrderScreeningReq.class);
        		BeanUtils.copyProperties(record, req);
            	record.setOrderNo(req.getOutApplicationNum()); //通华订单号
        		record.setSeriNo(req.getApplicationNum());  //大数订单号
        		record.setStatus(req.getResult().equals("1")?"02":"03");  //更改初筛通过(1)/不通过(0)对应状态
            	if(null == applyOrderMapper.selectByOrder(record)) { //插入
            		logger.error("不存在初筛数据");
                    resp = BasicResp.back(ServiceEnum.APPLY_INFO_MISSING.getCode(), ServiceEnum.APPLY_INFO_MISSING.getDesc());
            	}else { //更新
            		applyOrderMapper.updateByOrderNoSelective(record);
            	}     
            	return resp;
            	
            }else if(ServiceEnum.SCORE_RESULT.getCode().equals(request.getEventType())){//评分通知（更新）
            	Map<String,String> map=(Map<String, String>) request.getData();
            	ApplyOrderScoreReq req =  com.thjk.bdf.common.utils.BeanUtil.decode(ApplyOrderScoreReq.class, map);

        		BeanUtils.copyProperties(record, req);
            	record.setSeriNo(req.getApplicationNum());
        		if(req.getResult().equals("0")) {//("0 ","07"), //评分拒绝
        			record.setStatus("07");
        		}else if(req.getResult().equals("1")){ //评分通过
        			record.setStatus("08");
        		}else {//评分异常
        			record.setStatus("09");
        		}
            	if(null == applyOrderMapper.selectBySeriNo(req.getApplicationNum())) { //插入
            		logger.error("不存在初筛数据");
                    resp = BasicResp.back(ServiceEnum.APPLY_INFO_MISSING.getCode(), ServiceEnum.APPLY_INFO_MISSING.getDesc());
            	}else { //更新
            		applyOrderMapper.updateBySeriNoSelective(record);
            	}  
            	return resp;
            	
            }else if(ServiceEnum.APPROVAL_RESULT.getCode().equals(request.getEventType())) { //审批结果通知（更新）
            	Map<String,String> map=(Map<String, String>) request.getData();
            	ApplyOrderApprovalReq req =  com.thjk.bdf.common.utils.BeanUtil.decode(ApplyOrderApprovalReq.class, map);
            	BeanUtils.copyProperties(record, req);
            	record.setSeriNo(req.getApplicationNum());
        		if(req.getResult().equals("0")) {// //审批拒绝
        			record.setStatus("05");
        		}else if(req.getResult().equals("1")){ //审批通过
        			record.setStatus("04");
        		}else {//审批异常
        			record.setStatus("06");
        		}
            	if(null == applyOrderMapper.selectBySeriNo(req.getApplicationNum())) { //插入
            		logger.error("不存在初筛数据");
                    resp = BasicResp.back(ServiceEnum.APPLY_INFO_MISSING.getCode(), ServiceEnum.APPLY_INFO_MISSING.getDesc());
            	}else { //更新
            		applyOrderMapper.updateBySeriNoSelective(record);
            	}     
            	return resp;
            }else if(ServiceEnum.CREDIT_INVALID_RESULT.getCode().equals(request.getEventType())) { //征信失效通知（更新）
            	Map<String,String> map=(Map<String, String>) request.getData(); 	
            	if(null == applyOrderMapper.selectBySeriNo(map.get("applicationNum"))) { //判断空
            		logger.error("不存在初筛数据");
                    resp = BasicResp.back(ServiceEnum.APPLY_INFO_MISSING.getCode(), ServiceEnum.APPLY_INFO_MISSING.getDesc());
            	}else { //更新
            		record.setSeriNo(map.get("applicationNum"));
                	record.setStatus("12");	//征信失效
                	record.setRemark(map.get("remark"));
            		applyOrderMapper.updateBySeriNoSelective(record);
            	}     
            	return resp;
            }else if(ServiceEnum.LIMIT_INVALID_RESULT.getCode().equals(request.getEventType())) { //额度失效通知（更新）
            	Map<String,String> map=(Map<String, String>) request.getData();
            	if(null == applyOrderMapper.selectBySeriNo(map.get("applicationNum"))) { //判断空
            		logger.error("不存在初筛数据");
                    resp = BasicResp.back(ServiceEnum.APPLY_INFO_MISSING.getCode(), ServiceEnum.APPLY_INFO_MISSING.getDesc());
            	}else { //更新
            		record.setSeriNo(map.get("applicationNum"));
                	record.setStatus("11");	//额度失效
                	record.setRemark(map.get("remark"));
            		applyOrderMapper.updateBySeriNoSelective(record);
            	}     
            	return resp;
            }else {
            	logger.error("不支持的通知类型：", request.getEventType());
            	resp = BasicResp.back(ServiceEnum.SERVICE_000006.getCode(), ServiceEnum.SERVICE_000006.getDesc());
            	return resp;
            }
		} catch (IllegalAccessException | InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			logger.error("授信通知异常", e);
            resp =  BasicResp.back(ServiceEnum.SERVICE_FAIL.getCode(), ServiceEnum.SERVICE_FAIL.getDesc());
            return resp;
		}
    }

}
